using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RecruitmentAgency.Models.DataTypes;
using RecruitmentAgency.Models.Utilities;
using RecruitmentAgency.Models.Validation;

namespace RecruitmentAgency.Controllers
{
    /// <summary>
    /// The RecruitmentAgency.Controllers.CvController provides interaction for the CV pages on the RecruitmentAgency web site
    /// </summary>
    public class CvController : BaseController
    {
        private List<string> titles, preferences, authorities, sectors, proficiency, skills, types, grades, qualifications, employments, referees, verifications, relationships, skillNames, qualificationTypes, qualificationSubjects, sectorPreferences;
        private CvValidator validator;
        private string selectMessage = "Please select an option from the list";
        private CvData cvData;

        /// <summary>
        /// Initialises a new RecruitmentAgency.Controllers.CvController instance
        /// </summary>
        public CvController() : base()
        {
            validator = new CvValidator(ModelState, selectMessage);
        }

        private void FillViewData()
        {
            titles = CommonMethods.AddSelectMessageToList(DataProvider.GetTitles());
            preferences = CommonMethods.AddSelectMessageToList(DataProvider.GetContactPreferences());
            authorities = CommonMethods.AddSelectMessageToList(DataProvider.GetAuthorityToWork());
            sectors = CommonMethods.AddSelectMessageToList(DataProvider.GetSectors());
            proficiency = CommonMethods.AddSelectMessageToList(DataProvider.GetproficiencyLevels());
            types = CommonMethods.AddSelectMessageToList(DataProvider.GetQualificationTypes());
            grades = CommonMethods.AddSelectMessageToList(DataProvider.GetGrades());
            verifications = CommonMethods.AddSelectMessageToList(DataProvider.GetVerificationTypes());
            relationships = CommonMethods.AddSelectMessageToList(DataProvider.GetRelationships());
            skills = new List<string>();
            qualifications = new List<string>();
            employments = new List<string>();
            referees = new List<string>();
        }
      
        /// <summary>
        /// This GET ViewCvs method returns a CvSearchData instance that contains one page of all CV results
        /// </summary>
        /// <param name="page">The page number of results required</param>
        /// <returns>A List of PersonalDetail instances</returns>
        public ActionResult ViewCvs(int? page)
        {
            if (Request.QueryString["pageSize"] != null) PageSize = int.Parse(Request.QueryString["pageSize"]);
            FillSearchPageViewData();
            int pageNumber = page.HasValue ? page.Value : 1;
            return View(DataProvider.SearchCvs(PageSize, pageNumber, -1, -1, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty));
        }

        /// <summary>
        /// This POST ViewCvs method returns a CvSearchData instance dependant on the search query
        /// </summary>
        /// <param name="page">The page number of results required</param>
        /// <param name="searchData">The CvSearchData instance that holds the search parameters from the form</param>
        /// <returns>A List of PersonalDetail instances</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ViewCvs(int? page, CvSearchData searchData)
        {
            FillSearchPageViewData();
            int pageNumber = page.HasValue ? page.Value : 1;
            int minimumNumberOfGcse, minimumNumberOfALevel;
            minimumNumberOfGcse = searchData.MinimumNumberOfGcse == string.Empty ? -1 : int.Parse(searchData.MinimumNumberOfGcse);
            minimumNumberOfALevel = searchData.MinimumNumberOfALevel == string.Empty ? -1 : int.Parse(searchData.MinimumNumberOfALevel);
            return View(DataProvider.SearchCvs(PageSize, pageNumber, minimumNumberOfGcse, minimumNumberOfALevel, searchData.JobSectorPreference, searchData.QualificationType, searchData.QualificationSubject, searchData.SkillName, searchData.PersonName));
        }

        /// <summary>
        /// This GET ViewCv method returns a CvData instance containing all of the CV details related to the input ID parameter
        /// </summary>
        /// <param name="id">The ID number of the user whose CV details are required</param>
        /// <returns>A CvData instance</returns>
        public ActionResult ViewCv(int id)
        {
            cvData = new CvData();
            cvData.CurrentUserId = id;
            CurrentPersonId = id;
            // select personal details (only AuthorityToWork needs verification)
            cvData.PersonalDetail = DataProvider.GetPersonalDetail(id);
            // select only verified records
            cvData.PersonQualifications = DataProvider.GetPersonQualifications(id).Where(q => q.QualificationVerified).ToList();
            cvData.PersonEmployments = DataProvider.GetPersonEmployment(id).Where(e => e.EmploymentVerified).ToList();
            cvData.PersonSkills = DataProvider.GetPersonSkills(id).Where(s => s.SkillVerified).ToList();
            cvData.PersonReferees = DataProvider.GetPersonReferees(id).Where(r => r.RefereeVerified).ToList();

            if (Request != null && Request.QueryString["pdf"] != null)
            {
                bool createPdf = false;
                bool.TryParse(Request.QueryString["pdf"], out createPdf);
                if (createPdf)
                {
                    string filePath = string.Format(@"C:\Windows\Temp\{0} {1} CV.pdf", cvData.PersonalDetail.FirstName, cvData.PersonalDetail.LastName);
                    PdfDocumentCreator pdfDocument = new PdfDocumentCreator(filePath);
                    pdfDocument.CreatePdfFromCvData(cvData);
                }
            }
            else if (Request != null && Request.QueryString["word"] != null)
            {
                bool createWord = false;
                bool.TryParse(Request.QueryString["word"], out createWord);
                if (createWord)
                {
                    string filePath = string.Format(@"C:\Windows\Temp\{0} {1} CV.doc", cvData.PersonalDetail.FirstName, cvData.PersonalDetail.LastName);
                    WordDocumentCreator wordDocument = new WordDocumentCreator(filePath);
                    wordDocument.CreateWordDocumentFromCvData(cvData);
                }
            }
            return View(cvData);
        }

        /// <summary>
        /// This GET Edit method returns a CvData instance containing all of the CV details related to the input ID parameter
        /// </summary>
        /// <param name="id">The ID number of the user whose CV details are required</param>
        /// <returns>A CvData instance</returns>
        public ActionResult Edit(int id)
        {
            FillViewData();
            PersonalDetail personalDetail = DataProvider.GetPersonalDetail(id);
            cvData = GetCvData(personalDetail, true, false);
            return View(cvData);
        }

        /// <summary>
        /// This POST Edit method updates any input values passed from the View via the Model and returns a CvData instance containing all of the CV details related to the input ID parameter
        /// </summary>
        /// <param name="id">The ID number of the user whose CV details are required</param>
        /// <param name="personalDetail">The PersonalDetail instance that is bound to the View</param>
        /// <param name="personQualification">The PersonQualification instance that is bound to the View</param>
        /// <param name="personEmployment">The PersonEmployment instance that is bound to the View</param>
        /// <param name="personSkill">The PersonSkill instance that is bound to the View</param>
        /// <param name="personReferee">The PersonReferee instance that is bound to the View</param>
        /// <param name="PhotoFileUpload">The HttpPostedFileBase instance that is bound to the PhotoFileUpload file input field and used for the PersonalDetail.PhotoUrl property</param>
        /// <returns>A CvData instance</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, PersonalDetail personalDetail, HttpPostedFileBase PhotoFileUpload, PersonQualification personQualification, PersonEmployment personEmployment, PersonSkill personSkill, PersonReferee personReferee)
        {
            FillViewData();
            cvData = new CvData();
            if (!ModelState.IsValid) return View();
            if (validator.ValidatePersonalDetails(personalDetail))
            {
                personalDetail.PersonId = id;
                SavePhoto(personalDetail, PhotoFileUpload);
                DataProvider.UpdatePersonDetails(personalDetail);
            }
            if (validator.ValidatePersonQualification(personQualification))
            {
                if (personQualification.PersonQualificationId != 0 || Request.QueryString["personQualificationId"] != null)
                {
                    if (personQualification.PersonQualificationId == 0) personQualification.PersonQualificationId = Convert.ToInt32(Request.QueryString["personQualificationId"]);
                    DataProvider.UpdateQualification(personQualification);
                }
            }
            if (validator.ValidatePersonEmployment(personEmployment))
            {
                if (personEmployment.EmploymentId != 0 || Request.QueryString["employmentId"] != null)
                {
                    if (personEmployment.EmploymentId == 0) personEmployment.EmploymentId = Convert.ToInt32(Request.QueryString["employmentId"]);
                    DataProvider.UpdateEmployment(personEmployment);
                }
            }
            if (validator.ValidatePersonSkill(personSkill))
            {
                if (personSkill.PersonSkillId != 0 || Request.QueryString["personSkillId"] != null)
                {
                    if (personSkill.PersonSkillId == 0) personSkill.PersonSkillId = Convert.ToInt32(Request.QueryString["personSkillId"]);
                    DataProvider.UpdateSkills(personSkill);
                }
            }
            if (validator.ValidatePersonReferee(personReferee))
            {
                if (personReferee.RefereeId != 0 || Request.QueryString["personRefereeId"] != null)
                {
                    if (personReferee.RefereeId == 0) personReferee.RefereeId = Convert.ToInt32(Request.QueryString["personRefereeId"]);
                    DataProvider.UpdateReferee(personReferee);
                }
            }
            cvData = GetCvData(DataProvider.GetPersonalDetail(id), true, false);
            return View(cvData);
        }

        /// <summary>
        /// This GET Create method returns a CvData instance containing all of the CV details related to the currently logged in user
        /// </summary>
        /// <returns>A CvData instance</returns>
        public ActionResult Create()
        {
            FillViewData();
            cvData = GetCvData(DataProvider.GetPersonalDetail(CurrentPersonId), false, false);
            return View(cvData);
        }


        /// <summary>
        /// This POST Create method adds any input values passed from the View via the Model and returns a CvData instance containing all of the CV details related to the input ID parameter
        /// </summary>
        /// <param name="id">The ID number of the user whose CV details are required</param>
        /// <param name="personalDetail">The PersonalDetail instance that is bound to the View</param>
        /// <param name="personQualification">The PersonQualification instance that is bound to the View</param>
        /// <param name="personEmployment">The PersonEmployment instance that is bound to the View</param>
        /// <param name="personSkill">The PersonSkill instance that is bound to the View</param>
        /// <param name="personReferee">The PersonReferee instance that is bound to the View</param>
        /// <param name="PhotoFileUpload">The HttpPostedFileBase instance that is bound to the PhotoFileUpload file input field and used for the PersonalDetail.PhotoUrl property</param>
        /// <returns>A CvData instance</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude = "UserId")]PersonalDetail personalDetail, HttpPostedFileBase PhotoFileUpload, [Bind(Exclude = "PersonSkillId")] PersonSkill personSkill, [Bind(Exclude = "PersonQualificationId")] PersonQualification personQualification, [Bind(Exclude = "EmploymentId")] PersonEmployment personEmployment, [Bind(Exclude = "RefereeId")] PersonReferee personReferee)
        {
            FillViewData();
            cvData = new CvData();
            if (!ModelState.IsValid) return View();
            if (validator.ValidatePersonalDetails(personalDetail))
            {
                personalDetail.PersonId = CurrentPersonId;
                SavePhoto(personalDetail, PhotoFileUpload);
                cvData.PersonalDetail = personalDetail;
                DataProvider.UpdatePersonDetails(personalDetail);
            }
            if (validator.ValidatePersonQualification(personQualification))
            {
                personQualification.PersonId = CurrentPersonId;
                cvData.PersonQualification = personQualification;
                if (personQualification.PersonQualificationId == 0) DataProvider.AddQualification(personQualification);
            }
            if (validator.ValidatePersonEmployment(personEmployment))
            {
                personEmployment.PersonId = CurrentPersonId;
                cvData.PersonEmployment = personEmployment;
                if (personEmployment.EmploymentId == 0) DataProvider.AddEmployment(personEmployment);
            }
            if (validator.ValidatePersonSkill(personSkill))
            {
                personSkill.PersonId = CurrentPersonId;
                cvData.PersonSkill = personSkill;
                if (personSkill.PersonSkillId == 0) DataProvider.AddSkill(personSkill);
            }
            if (validator.ValidatePersonReferee(personReferee))
            {
                personReferee.PersonId = CurrentPersonId;
                cvData.PersonReferee = personReferee;
                if (personReferee.RefereeId == 0) DataProvider.AddReferee(personReferee);
            }
            cvData = GetCvData(DataProvider.GetPersonalDetail(CurrentPersonId), false, false);
            return View(cvData);
        }

        /// <summary>
        /// This GET Delete method returns a PersonalDetail instance relating to the input ID parameter to be deleted
        /// </summary>
        /// <param name="id">The ID number of the user whose personal details are to be deleted</param>
        /// <returns>A PersonalDetail instance</returns>
        public ActionResult Delete(int id)
        {
            return View(DataProvider.GetPersonalDetail(id));
        }

        /// <summary>
        /// This POST Delete method deletes the input PersonalDetail and all related records via the Model then redirects to the GET ViewCvs method which returns a List of PersonalDetail instances
        /// </summary>
        /// <param name="id">The ID number of the user to be deleted</param>
        /// <param name="personalDetail">The PersonalDetail instance of the user to be deleted</param>
        /// <returns>A redirect to the ViewCvs page</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id, PersonalDetail personalDetail)
        {
            DataProvider.DeletePerson(id);
            return RedirectToAction("ViewCvs");
        }

        /// <summary>
        /// This GET DeleteRecord method returns a CvData instance containing all of the CV details related to the input ID parameter
        /// </summary>
        /// <param name="id">The ID number of the user whose CV details are required</param>
        /// <returns>A CvData instance</returns>
        public ActionResult DeleteRecord(int id)
        {
            cvData = GetCvData(DataProvider.GetPersonalDetail(id), true, true);
            return View(cvData);
        }

        /// <summary>
        /// This POST DeleteRecord method deletes the relevant input data type passed from the View via the Model then redirects to the GET DeleteRecord method which returns a CvData instance containing all of the CV details related to the input ID parameter
        /// </summary>
        /// <param name="id">The ID number of the user whose record is to be deleted</param>
        /// <param name="personQualification">The PersonQualification instance that is bound to the View</param>
        /// <param name="personEmployment">The PersonEmployment instance that is bound to the View</param>
        /// <param name="personSkill">The PersonSkill instance that is bound to the View</param>
        /// <param name="personReferee">The PersonReferee instance that is bound to the View</param>
        /// <returns>A CvData instance</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteRecord(int id, PersonQualification personQualification, PersonEmployment personEmployment, PersonSkill personSkill, PersonReferee personReferee)
        {
            //if (!ModelState.IsValid) return View();
            if (!personQualification.IsNull) // determine if the PersonQualification is to be deleted
            {
                if (personQualification.PersonQualificationId != 0 || Request.QueryString["personQualificationId"] != null)
                {
                    if (personQualification.PersonQualificationId == 0) personQualification.PersonQualificationId = Convert.ToInt32(Request.QueryString["personQualificationId"]);
                    DataProvider.DeleteQualification(personQualification.PersonQualificationId);
                }
            }
            if (!personEmployment.IsNull) // determine if the PersonEmployment is to be deleted
            {
                if (personEmployment.EmploymentId != 0 || Request.QueryString["employmentId"] != null)
                {
                    if (personEmployment.EmploymentId == 0) personEmployment.EmploymentId = Convert.ToInt32(Request.QueryString["employmentId"]);
                    DataProvider.DeleteEmployment(personEmployment.EmploymentId);
                }
            }
            if (!personSkill.IsNull) // determine if the PersonSkill is to be deleted
            {
                if (personSkill.PersonSkillId != 0 || Request.QueryString["personSkillId"] != null)
                {
                    if (personSkill.PersonSkillId == 0) personSkill.PersonSkillId = Convert.ToInt32(Request.QueryString["personSkillId"]);
                    DataProvider.DeleteSkill(personSkill.PersonSkillId);
                }
            }
            if (!personReferee.IsNull) // determine if the PersonReferee is to be deleted
            {
                if (personReferee.RefereeId != 0 || Request.QueryString["personRefereeId"] != null)
                {
                    if (personReferee.RefereeId == 0) personReferee.RefereeId = Convert.ToInt32(Request.QueryString["personRefereeId"]);
                    DataProvider.DeleteReferee(personReferee.RefereeId);
                }
            }
            return RedirectToAction("DeleteRecord", new { id = id });
        }

        /// <summary>
        /// Returns a RSS feed of CV data in ATOM1.0 format
        /// </summary>
        /// <returns>A RSS feed of CV data in ATOM1.0 format</returns>
        public ActionResult CvRssFeed()
        {
            return new RssFeedActionResult() { Feed = DataProvider.GetCvRssFeed(Request.Url.AbsoluteUri.Replace("CvRssFeed", string.Empty))};
        }

        private CvData GetCvData(PersonalDetail personalDetail, bool fillFormFields, bool isDeletePage)
        {
            cvData = new CvData();
            if (personalDetail == null) return cvData;
            cvData.CurrentUserId = personalDetail.PersonId;
            // fill common drop down lists
            if (!isDeletePage) ViewData["titles"] = new SelectList(titles, personalDetail.Title);
            if (!isDeletePage) ViewData["preferences"] = new SelectList(preferences, personalDetail.ContactPreference);
            if (!isDeletePage) ViewData["authorities"] = new SelectList(authorities, personalDetail.AuthorityToWork);
            if (!isDeletePage) ViewData["jobSectors"] = new SelectList(sectors, personalDetail.JobSectorPreference);
            // only if user is admin role!!!!!!!!!!!!!
            if (true && !isDeletePage) ViewData["personalDetailVerifications"] = new SelectList(verifications, personalDetail.PersonalDetailVerificationType);

            // get skills that relate to the input personalDetail
            List<PersonSkill> personSkills = DataProvider.GetPersonSkills(personalDetail.PersonId);
            PersonSkill skill = new PersonSkill();
            if (personSkills.Count > 0 && fillFormFields)
            {
                if (Request.QueryString["personSkillId"] != null)
                {
                    int personSkillId = 0;
                    int.TryParse(Request.QueryString["personSkillId"], out personSkillId);
                    skill = (from s in personSkills where s.PersonSkillId == personSkillId select s).SingleOrDefault();
                }
                else skill = personSkills[0];
                if (!isDeletePage) ViewData["proficiency"] = new SelectList(proficiency, skill.ProficiencyLevel);
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["skillVerifications"] = new SelectList(verifications, skill.SkillVerificationType);
            }
            else
            {
                if (!isDeletePage) ViewData["proficiency"] = new SelectList(proficiency);
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["skillVerifications"] = new SelectList(verifications);
            }
            ViewData["skills"] = personSkills;

            // get qualifications that relate to the input personalDetail
            List<PersonQualification> personQualifications = DataProvider.GetPersonQualifications(personalDetail.PersonId);
            PersonQualification qualification = new PersonQualification();
            if (personQualifications.Count > 0 && fillFormFields)
            {
                if (Request.QueryString["personQualificationId"] != null)
                {
                    int personQualificationId = 0;
                    int.TryParse(Request.QueryString["personQualificationId"], out personQualificationId);
                    qualification = (from q in personQualifications where q.PersonQualificationId == personQualificationId select q).SingleOrDefault();
                }
                else qualification = personQualifications[0];
                if (!isDeletePage) ViewData["types"] = new SelectList(types, qualification.Type);
                if (!isDeletePage) ViewData["grades"] = new SelectList(grades, qualification.Result);
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["qualificationVerifications"] = new SelectList(verifications, qualification.QualificationVerificationType);
            }
            else
            {
                qualification.PersonId = personalDetail.PersonId;
                if (!isDeletePage) ViewData["types"] = new SelectList(types);
                if (!isDeletePage) ViewData["grades"] = new SelectList(grades);
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["qualificationVerifications"] = new SelectList(verifications);
            }
            ViewData["qualifications"] = personQualifications;

            // get employment that relate to the input personalDetail
            List<PersonEmployment> personEmployments = DataProvider.GetPersonEmployment(personalDetail.PersonId);
            PersonEmployment employment = new PersonEmployment();
            if (personEmployments.Count > 0 && fillFormFields)
            {
                if (Request.QueryString["employmentId"] != null)
                {
                    int employmentId = 0;
                    int.TryParse(Request.QueryString["employmentId"], out employmentId);
                    employment = (from e in personEmployments where e.EmploymentId == employmentId select e).SingleOrDefault();
                    if (!isDeletePage) ViewData["sectors"] = new SelectList(sectors, employment.IndustrySector);
                }
                else
                {
                    employment = personEmployments[0];
                    if (!isDeletePage) ViewData["sectors"] = new SelectList(sectors, personEmployments[0].IndustrySector);
                }
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["employmentVerifications"] = new SelectList(verifications, employment.EmploymentVerificationType);
            }
            else
            {
                employment.PersonId = personalDetail.PersonId;
                if (!isDeletePage) ViewData["sectors"] = new SelectList(sectors);
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["employmentVerifications"] = new SelectList(verifications);
            }
            ViewData["employments"] = personEmployments;

            // get referees that relate to the input personalDetail
            List<PersonReferee> personReferees = DataProvider.GetPersonReferees(personalDetail.PersonId);
            PersonReferee referee = new PersonReferee();
            if (personReferees.Count > 0 && fillFormFields)
            {
                if (Request.QueryString["personRefereeId"] != null)
                {
                    int personRefereeId = 0;
                    int.TryParse(Request.QueryString["personRefereeId"], out personRefereeId);
                    referee = (from p in personReferees where p.RefereeId == personRefereeId select p).SingleOrDefault();
                    if (!isDeletePage) ViewData["relationships"] = new SelectList(relationships, referee.Relationship);
                }
                else
                {
                    referee = personReferees[0];
                    if (!isDeletePage) ViewData["relationships"] = new SelectList(relationships, personReferees[0].Relationship);
                }
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["refereeVerifications"] = new SelectList(verifications, referee.RefereeVerificationType);
            }
            else
            {
                if (!isDeletePage) ViewData["relationships"] = new SelectList(relationships);
                // only if user is admin role!!!!!!!!!!!!!
                if (true && !isDeletePage) ViewData["refereeVerifications"] = new SelectList(verifications);
            }
            ViewData["referees"] = personReferees;

            // fill cvData model to pass to the Views
            cvData.PersonalDetail = personalDetail;
            cvData.PersonQualification = qualification;
            cvData.PersonQualifications = personQualifications;
            cvData.PersonEmployment = employment;
            cvData.PersonSkill = skill;
            cvData.PersonReferee = referee;
            return cvData;
        }

        private void FillSearchPageViewData()
        {
            sectors = CommonMethods.AddInputMessageToList(DataProvider.GetSectors(), string.Empty);
            ViewData["sectors"] = new SelectList(sectors);
            skillNames = CommonMethods.AddInputMessageToList(DataProvider.GetUniqueSkillNames(), string.Empty);
            ViewData["skillNames"] = new SelectList(skillNames);
            qualificationTypes = CommonMethods.AddInputMessageToList(DataProvider.GetUniqueQualificationTypeNames(), string.Empty);
            ViewData["qualificationTypes"] = new SelectList(qualificationTypes);
            qualificationSubjects = CommonMethods.AddInputMessageToList(DataProvider.GetUniqueQualificationSubjectNames(), string.Empty);
            ViewData["qualificationSubjects"] = new SelectList(qualificationSubjects);
            sectorPreferences = CommonMethods.AddInputMessageToList(DataProvider.GetUniqueSectorPreferences(), string.Empty);
            ViewData["sectorPreferences"] = new SelectList(sectorPreferences);
            ViewData["pageSizes"] = new SelectList(DefaultPageSizes, PageSize);
        }

        private void SavePhoto(PersonalDetail personalDetail, HttpPostedFileBase PhotoUrl)
        {
            if (PhotoUrl != null && PhotoUrl.ContentLength > 0)
            {
                string filePath = Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, string.Empty) + "/Images/PersonPhotos/";
                string fileType = PhotoUrl.FileName.Substring(PhotoUrl.FileName.LastIndexOf("."));
                string imageName = personalDetail.FirstName + personalDetail.LastName + personalDetail.PersonId + "Photo" + fileType;
                string photoUrlToStore = filePath + imageName;
                string photoUrl = Path.Combine(HttpContext.Server.MapPath("~/Images/PersonPhotos"), imageName);
                //Image photo = Image.FromStream(PhotoUrl.InputStream, true, true);
                //Image photo2 = CommonMethods.ResizeImage(Image.FromStream(PhotoUrl.InputStream, true, true), 145, 145, false);
                Image photo = CommonMethods.ResizeImage(Image.FromStream(PhotoUrl.InputStream, true, true), 135, 135);
                photo.Save(photoUrl);
                // save image on server
                //PhotoUrl.SaveAs(photoUrl);
                personalDetail.PhotoUrl = photoUrlToStore;
            }
        }
    }
}